﻿using SqlSugar;

namespace Inventorycount.Infrastructure
{
    public class SqlSugarHelp<T> where T : class, new()
    {
        private readonly ISqlSugarClient sqlSugarClient;
        public SqlSugarHelp(ISqlSugarClient sqlSugarClient)
        {
            this.sqlSugarClient = sqlSugarClient;
        }
        public ISqlSugarClient SqlSugarClient => sqlSugarClient;
        //添加
        public Task<int> AddAsync(T t)
        {
            var i = sqlSugarClient.Insertable(t).ExecuteCommandAsync();
            return i;
        }
        //批量添加b.Insertable(List<实体>).ExecuteCommand() 
        public Task<int> AddRange(List<T> t)
        {
            var i = sqlSugarClient.Insertable(t).ExecuteCommandAsync();
            return i;
        }
        //删除
        public Task<int> DeleteAsync(T t)
        {
            var i = sqlSugarClient.Deleteable(t).ExecuteCommandAsync();
            return i;
        }
        //修改
        public Task<int> UpdateAsync(T t)
        {
            var i = sqlSugarClient.Updateable(t).ExecuteCommandAsync();
            return i;
        }
        //批量修改
        public Task<int> UpdateRange(List<T> entities)
        {
            var i = sqlSugarClient.Updateable(entities).ExecuteCommandAsync();
            return i;
        }
        // 使用事务执行多个操作
        public async Task<int> UseTransactionAsync(Func<Task<int>> action)
        {
            int result = 0;
            try
            {
                // 开始事务
                sqlSugarClient.Ado.BeginTran();
                result = await action();
                // 提交事务
                sqlSugarClient.Ado.CommitTran();
            }

            catch (Exception ex)
            {
                // 回滚事务
                sqlSugarClient.Ado.RollbackTran();
                throw ex; // 重新抛出异常
            }
            return result;
        }
        //返回ID
        public async Task<int> AddId(T t)
        {
            int id = await sqlSugarClient.Insertable(t).ExecuteReturnIdentityAsync();
            return id;
        }
        //
        public async Task<int> InsertReturnIdentityAsync(T entity)
        {
            return await SqlSugarClient.Insertable(entity).ExecuteReturnIdentityAsync();
        }
        //确保整个项目中批量插入的方法命名一致
        public async Task<int> InsertRangeAsync(List<T> entities)
        {
            return await SqlSugarClient.Insertable(entities).ExecuteCommandAsync();
        }
    }
    }
